package com.lss.myapp.util;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    private static final OkHttpClient client = new OkHttpClient();
    private static final Handler uiHandler = new Handler(Looper.getMainLooper());

    /**
     * 异步POST请求（自动切换UI线程）
     * todo 构建的请求提存在问题
     *
     * @param url     完整请求地址
     * @param params  请求参数键值对
     * @param success 成功回调（在UI线程执行）
     * @param failure 失败回调（在UI线程执行）
     */
    public static void postAsync(String url, Map<String, String> params,
                                 OnSuccess success, OnFailure failure) {
        // 构建请求体
//        FormBody.Builder builder = new FormBody.Builder();
//        for (Map.Entry<String, String> entry : params.entrySet()) {
//            builder.add(entry.getKey(), entry.getValue());
//        }
        // 构建请求体
        RequestBody requestBody = new FormBody.Builder()
                .add("mobile", params.get("mobile"))
                .add("password", params.get("password"))  // 注意：实际项目中应加密传输密码
                .build();
        // 创建请求对象
        Request request = new Request.Builder()
                .url(url)
                .addHeader("contentType", "application/json;charset=UTF-8")
                .post(requestBody)
                .build();

        // 发起异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.post(() -> failure.onFailure(e));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (!response.isSuccessful()) {
                        throw new IOException("HTTP Code: " + response.code());
                    }

                    final String responseData = response.body() != null ?
                            response.body().string() : "";

                    uiHandler.post(() -> success.onSuccess(responseData));
                } catch (IOException e) {
                    uiHandler.post(() -> failure.onFailure(e));
                } finally {
                    response.close();
                }
            }
        });
    }

    /**
     * 成功回调接口
     */
    public interface OnSuccess {
        void onSuccess(String response);
    }

    /**
     * 失败回调接口
     */
    public interface OnFailure {
        void onFailure(Exception e);
    }
}